import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from 'axios'
import Cookies from 'js-cookie'
import NproGress from 'nprogress'
import { message } from 'antd'
import WhiteList from './WhiteList'
import "nprogress/nprogress.css"

const ins: AxiosInstance = axios.create({
    baseURL: "/api",
    timeout: 6000
})

ins.interceptors.request.use((config: AxiosRequestConfig) => {
    // config.headers.Authorization = "token"
    NproGress.start()
    const Authorization = Cookies.get('token') ? Cookies.get('token') : ''
    if (config.headers) {
        // config.headers.common["Authorization"] = token
        config.headers = {
            ...config.headers,
            Authorization,
        };
        // (config.headers as AxiosRequestHeaders).token = token
    }

    return config
})

ins.interceptors.response.use((data: AxiosResponse<any>) => {  
    console.log(data)
    let flag = WhiteList.some(item => item.method === data.config.method && data.config.url.includes(item.url) )
    if (flag) {
        if (data.status === 200) {
            message.success("请求成功")
        }
    }
    NproGress.done()
    return data
}, (error) => {
    switch (error.response.status) {
        case 422:
            message.error("无法响应")
            break;
    }
})

export default ins